package com.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BaseServiceImpl;
import com.conf.web.FileDel;
import com.constant.PowerEnum;
import com.constant.StateEnum;
import com.entity.Artical;
import com.entity.Users;
import com.entity.VipManage;
import com.exception.ServiceException;
import com.repository.UserRepository;
import com.req.UserPageReq;
import com.req.UserReq;
import com.base.BasePageRes;
import com.res.UserRes;
import com.service.UserService;
import com.util.DateUtils;
import com.util.RedisUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Objects;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserReq, UserRes, UserRepository, Users> implements UserService {
    @Autowired
    private FileDel fileDel;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private VipManageServiceImpl vipManageService;
    @Override
    public UserRes saveUser(UserReq userReq) {
        return this.handle(userReq);
    }



    @Override
    public UserRes update(UserReq userReq) {
        Users users = this.queryT(userReq);
        //头像为空之前的头像不删除
        if(!StringUtils.isEmpty(userReq.getFace())){
            if(!Objects.equals(userReq.getFace(),users.getFace())){
                fileDel.del(users.getFace());
            }
        }
        else{
            userReq.setFace(users.getFace());
        }
        //密码查询出来的不一样说明改了密码。
        if(!Objects.equals(userReq.getPassword(),users.getPassword())){
            userReq.setPassword(StringUtil.md5(userReq.getPassword()));
        }

        return super.update(userReq);
    }

    @Override
    public UserRes del(UserReq userReq) {
        Users users = this.queryT(userReq);
        fileDel.del(users.getFace());
        return super.del(userReq);
    }

    /**
     * 密码需要加密处理
     *
     * @param userReq
     * @return
     */
    @Override
    public UserRes add(UserReq userReq) {
        if(StringUtils.isEmpty(userReq.getId())){
            throw new ServiceException("账号不能为空");
        }
        String password = userReq.getPassword();
        if (StringUtils.isEmpty(password)) {
            throw new ServiceException("密码不能为空");
        }
        String md5Password = StringUtil.md5(userReq.getPassword());
        userReq.setPassword(md5Password);
        return super.add(userReq);
    }

    @Override
    public BasePageRes queryPage(UserPageReq pageReq,UserRes userRes) {
        if (StringUtils.isEmpty(pageReq.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(pageReq.getSize())) {
            throw new ServiceException("请传入size");
        }
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        PowerEnum powerEnum = PowerEnum.codeOf(userRes.getPower());
        switch (powerEnum) {
            case Admin:
                break;
            case Users:
                wrapper.lambda().and(Wrapper -> Wrapper.eq(Users::getId, userRes.getId()));
                break;
            default:
                break;
        }


        wrapper.lambda().orderByDesc(Users::getCrDate);
        if (!StringUtils.isEmpty(pageReq.getDescre())) {
            wrapper.lambda().and(Wrapper->Wrapper.like(Users::getId, pageReq.getDescre()).
                    or().like(Users::getNickName, pageReq.getDescre())
                    .or().like(Users::getMail, pageReq.getDescre()))
            ;

        }


           IPage<Users> pages = new Page<>(pageReq.getPage(), pageReq.getSize());
        IPage<Users> articalIPage = this.page(pages, wrapper);
        BasePageRes pageRes = this.convertIpage(articalIPage, new UserRes());

        return pageRes;
    }

    @Override
    public UserRes login(UserReq userReq) {
        if(StringUtils.isEmpty(userReq.getId())){
            throw new ServiceException("账号不能为空");
        }
        if(StringUtils.isEmpty(userReq.getPassword())){
            throw new ServiceException("密码不能为空");
        }
        String md5Password = StringUtil.md5(userReq.getPassword());
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .and(Wrapper->Wrapper.eq(Users::getId,userReq.getId()).or().eq(Users::getMail,userReq.getMail()));

        Users users = getOne(queryWrapper);
        if(users == null){
            throw new ServiceException("账号或邮箱不存在");
        }
       queryWrapper.lambda().and(Wrapper -> Wrapper.eq(Users::getPassword, md5Password));
        users = getOne(queryWrapper);
        if(users==null){
            throw new ServiceException("密码输入错误");
        }
        String key = RedisUtil.generateLoginKey(users.getId());
        UserRes userRes = new UserRes();
        BeanUtil.copyProperties(users,userRes);
        userRes.setKey(key);
        userRes.setCrDate(DateUtils.parseDate(userRes.getCrDate(),DateUtils.YYYY_MM_DD_HH_MM_SS));
        //查询会员 暂时只做时间会员，数量下载会员不管 会员结束日期要大于现在的就是有效的
        QueryWrapper<VipManage> vipManageQueryWrapper = new QueryWrapper<>();
        vipManageQueryWrapper.lambda().eq(VipManage::getUserId,users.getId())
                .eq(VipManage::getIsAvailable, StateEnum.YES.getCode())
                .eq(VipManage::getVipType,StateEnum.TIME.getCode())
        .orderByDesc(VipManage::getEndDate)
        ;
        VipManage vipManage = vipManageService.getOne(vipManageQueryWrapper);
        if(vipManage!=null) {
            if (vipManage.getEndDate().getTime() >= DateUtils.getNow().getTime()) {
                userRes.setVip(StateEnum.YES.getCode());
            }
        }

        //存入redis 24小时过期
        redisTemplate.opsForValue().set(key, JSONObject.toJSONString(userRes));

        return userRes;
    }

    @Override
    public void logout(UserRes res) {
        String key = RedisUtil.generateLoginKey(res.getId());
        redisTemplate.delete(key);
    }
}
